package cn.rwklyd.BookKeeping.pojo.vo;

import cn.rwklyd.BookKeeping.pojo.Permission;
import cn.rwklyd.BookKeeping.pojo.User;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Data
@NoArgsConstructor
@Slf4j
@Tag(name = "Securtiy验证用户信息")

/*
    创建UserDetails对象
 */
public class LoginUser implements UserDetails {
    @Schema(description = "登录的用户信息")
    private User user;
    @Schema(description = "用户权限列表")
    private List<Permission> permissions;

    public LoginUser(User user, List<Permission> permissions) {
        this.user = user;
        this.permissions = permissions;
    }

    List<SimpleGrantedAuthority> authorities;   // 权限信息集合

    // 返回用用户信息
    public User getUser() {
        return user;
    }

    // 返回用户密码
    @Override
    public String getPassword() {
        return user.getPassword();
    }

    // 返回用户姓名
    @Override
    public String getUsername() {
        return user.getUsername();
    }

    // 返回用户权限集合
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if(authorities!=null){
            return authorities;
        }
        authorities = new ArrayList<>();
        for (Permission permission : permissions) {
            authorities.add(new SimpleGrantedAuthority(permission.getPermissionName()));
        }
        return authorities;
    }

    // 账号是否未过期
    @Override
    public boolean isAccountNonExpired() {
        return UserDetails.super.isAccountNonExpired();
    }

    // 账户是否未锁定
    @Override
    public boolean isAccountNonLocked() {
        return user.getStatus() != User.UserStatus.locked;
//        return UserDetails.super.isAccountNonLocked();
    }

    // 判断账号是否没有超时
    @Override
    public boolean isCredentialsNonExpired() {
        return UserDetails.super.isCredentialsNonExpired();
    }

    // 账户是否可用
    @Override
    public boolean isEnabled() {
        return UserDetails.super.isEnabled();
    }


}
